//
//  NetworkServer.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/10/27.
//

#import "NetworkServer.h"

static NSTimeInterval kTimeOutInterval = 60.0f;
static AFHTTPSessionManager *_manager;

@implementation NetworkServer


+ (AFHTTPSessionManager *_Nonnull)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager =  [self managerWithBaseURL:nil sessionConfiguration:NO];
    });
    
    return _manager;
}

#pragma mark - 网络请求类
/// POST请求
+ (NSURLSessionDataTask *_Nullable)postWithUrl:(NSString *_Nonnull)urlString httpHeader:(NSDictionary * _Nullable)httpHeader httpBody:(NSDictionary *_Nullable)httpBody progress:(ProgressBlock _Nullable)progress success:(RequestSuccessBlock _Nullable)success failure:(RequestFailureBlock _Nullable)failure {
    AFHTTPSessionManager *manager = [self shareManager];
    [self configRequestHttpHeader:httpHeader];
    NSURLSessionDataTask *dataTask = [manager POST:urlString parameters:httpBody headers:nil progress:progress success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task, responseObject);
        }
    } failure:failure];
    return dataTask;
}

/// GET请求
+ (NSURLSessionDataTask *_Nullable)getWithUrl:(NSString *_Nonnull)urlString httpHeader:(NSDictionary * _Nullable)httpHeader httpBody:(NSDictionary *_Nullable)httpBody progress:(ProgressBlock _Nullable)progress success:(RequestSuccessBlock _Nullable)success failure:(RequestFailureBlock _Nullable)failure {
    AFHTTPSessionManager *manager = [self shareManager];
    [self configRequestHttpHeader:httpHeader];
    NSURLSessionDataTask *dataTask = [manager GET:urlString parameters:httpBody headers:nil progress:progress success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task, responseObject);
        }
    } failure:failure];
    return dataTask;
}

/// 上传文件
+ (NSURLSessionDataTask *_Nullable)uploadWithURL:(NSString *_Nonnull)urlString httpHeader:(NSDictionary * _Nullable)httpHeader httpBody:(NSDictionary *_Nullable)httpBody fileData:(NSArray *_Nonnull)fileDataArr fileNames:(NSArray *_Nullable)fileNames mimeType:(NSString *_Nullable)mimeType progress:(ProgressBlock _Nullable)progress success:(RequestSuccessBlock _Nullable)success failure:(RequestFailureBlock _Nullable)failure {
    AFHTTPSessionManager *manager = [self shareManager];
    [self configRequestHttpHeader:httpHeader];
    NSURLSessionDataTask *dataTask = [manager POST:urlString parameters:httpBody headers:nil constructingBodyWithBlock:^(id <AFMultipartFormData>  _Nonnull formData) {
        [fileDataArr enumerateObjectsUsingBlock:^(NSData *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *imageKey;
            NSString *fileName;
            if ([fileNames isKindOfClass:[NSArray class]] && fileNames.count > idx) {
                imageKey = fileNames[idx];
            }else {
                imageKey = [NSString stringWithFormat:@"file_%02ld",(long)idx + 1];
            }
            if (mimeType.intValue == 1) {
                fileName = [NSString stringWithFormat:@"%@.mp4",imageKey];
            }else {
                fileName = [NSString stringWithFormat:@"%@.jpg",imageKey];
            }
            [formData appendPartWithFileData:obj name:imageKey fileName:fileName mimeType:(mimeType.intValue == 1 ? @"video/*" : @"text/plain")];
        }];
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask *_Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task, responseObject);
        }
    } failure:failure];
    return dataTask;
}

#pragma mark - private
+ (AFHTTPSessionManager *)managerWithBaseURL:(NSString *)baseURL sessionConfiguration:(BOOL)isconfiguration {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *manager = nil;
    NSURL *url;
    if (baseURL) {
        url = [NSURL URLWithString:baseURL];
    }
    
    if (isconfiguration) {
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:configuration];
    } else {
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
    }
    
    manager.operationQueue.maxConcurrentOperationCount = 4;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = kTimeOutInterval;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    manager.responseSerializer = response;
    /// 此方法用来删除value值为null的键值对
    response.removesKeysWithNullValues = YES;
    
    return manager;
}

/// 配置httpHeader参数
+ (void)configRequestHttpHeader:(NSDictionary *)httpHeader {
    if ([httpHeader isKindOfClass:[NSDictionary class]]) {
        [httpHeader enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [[self shareManager].requestSerializer setValue:obj forHTTPHeaderField:key];
        }];
    }
}

@end
